package com.itmck.interceptor;

import cn.hutool.core.util.ReflectUtil;
import com.itmck.interceptor.annotation.DecryptTransaction;
import com.itmck.interceptor.annotation.EncryptTransaction;
import com.itmck.util.DesEncryptThreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Objects;

@Slf4j
@Component
public class DesEncryptFactoryImpl implements DesEncryptFactory {


    @Override
    public <T> T encrypt(Field[] declaredFields, T paramsObject) {

        for (Field field : declaredFields) {
            EncryptTransaction encryptTransaction = field.getAnnotation(EncryptTransaction.class);
            if (!Objects.isNull(encryptTransaction)) {
                log.debug("当前字段:{} 标注有:@EncryptTransaction注解,需要进行加密处理", field.getName());
                if (field.getType().equals(String.class)) {
                    Object object = ReflectUtil.getFieldValue(paramsObject, field);
                    if (null != object) {
                        ReflectUtil.setFieldValue(paramsObject, field, DesEncryptThreeUtil.encode3Des((String) object));
                    }
                }
            }
        }
        return paramsObject;
    }

    @Override
    public <T> T decrypt(T result) {
        Field[] declaredFields = ReflectUtil.getFields(result.getClass());
        for (Field field : declaredFields) {
            //取出所有被DecryptTransaction注解的字段
            DecryptTransaction decryptTransaction = field.getAnnotation(DecryptTransaction.class);
            if (!Objects.isNull(decryptTransaction)) {
                log.debug("当前字段:{} 标注有:@DecryptTransaction注解,需要进行解密处理", field.getName());
                //String的解密
                if (field.getType().equals(String.class)) {
                    Object object = ReflectUtil.getFieldValue(result, field);
                    if (null != object) {
                        ReflectUtil.setFieldValue(result, field, DesEncryptThreeUtil.decode3Des((String) object));
                    }
                }
            }
        }
        return result;
    }
}
